// 导入express
const express = require('express')
// 导入cors
const cors = require('cors')

// 创建服务器
const app = express()
// 注册解决跨域问题中间件
app.use(cors())
// 注册内置中间件
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(express.static('public'))

// 监听GET请求
app.get('/ping', (req, res) => {
    console.log("ping pong!")
    return res.send({data: 'pong!'})
})


// 全局变量
// 刷新token
let refreshToken = '';

const getTokenUrl = `http://wkartist.enterprise.com/portal/sharing/rest/oauth2/token`
const clientId = "qSQ7iaZg0IiZr5C0";
const clientSecret = '1b9c93aa38fd426a9cf2377b1ec43487'
const callbackUrl = "https://arc11Linux.enterprise.com/callback"
const mapAppHomeUrl = "https://wkartist.enterprise.com/apidemo/oauthtest.html"


// auth重定向接口
app.get('/callback', (req, res) => {
    let code = req.query.code
    console.log("code: "+code)

    let formData = new FormData()
    formData.append('client_id', clientId)
    formData.append('code', code)
    formData.append('client_secret', clientSecret)
    formData.append('redirect_uri', callbackUrl)
    formData.append('grant_type', 'authorization_code')

    fetch(getTokenUrl , {
        method: 'POST',
        body: formData
    }).then(function(response) {
        if(response.status === 200){
            return response.json();
        }else{
            return {};
        }
    }).then(function(data){
        console.log(data)
        if (data.access_token) {
            // 保存refresh_token至缓存中
            refreshToken = data.refresh_token
            return res.redirect(`${mapAppHomeUrl}#access_token=${data.access_token}&expires_in=${data.expires_in}&username=${data.username}`);
        }
    }).catch(function(err){
        console.log(err);
        return res.send({error: err.message})
    })

})

// 刷新token
app.get('/refreshToken', (req, res) => {
    let formData = new FormData()
    formData.append('client_id', clientId)
    formData.append('grant_type', 'refresh_token')
    formData.append('refresh_token', refreshToken)

    fetch(getTokenUrl , {
        method: 'POST',
        body: formData
    }).then(function(response) {
        if(response.status === 200){
            return response.json();
        }else{
            return {};
        }
    }).then(function(data){
        console.log(data)
        if (data.access_token) {
            return res.json({
                code: 200,
                access_token: data.access_token,
                expires_in: data.expires_in,
                username: data.username
            });
        }
        // 如果refresh_token过期
        if (data.error.code === 498) {
            return res.json({
                code: data.error.code,
                msg: "refresh_token已过期请重新授权"
            })
        }
    }).catch(function(err){
        console.log(err);
        return res.send({error: err.message})
    })
})


// 调用listen启动服务器
app.listen(3001, () => {
    console.log('Server is running on port 3001')
})
